package com.bilibili.sys.servlet;

import com.bilibili.sys.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author alpha
 * @program: BookSystem
 * @description: 处理文件下载的servlet
 * @since 2024-03-26 20:48
 **/
@WebServlet(name = "downloadServlet", urlPatterns = {"/sys/downloadServlet"})
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //文件下载的操作
        //获取需要下载的文件的名称
        String fileName = req.getParameter("fileName");
        //对应的文件存储的基本路径
        String basePath = Constant.UPLOAD_DIRECTORY;
        //处理文件下载的操作
        FileInputStream fileInputStream = new FileInputStream(basePath + File.separator + fileName);
        //获取需要下载的文件长度
        int size = fileInputStream.available();
        byte[] data = new byte[size];
        //读取数据到字节数组中
        fileInputStream.read(data);
        fileInputStream.close();
        //响应的信息需要让浏览器知道我们返回的是什么信息
        if (fileName.contains(".jpg") || fileName.contains(".png")) {
            //说明下载的是图片
            resp.setContentType("image/jpg");
        } else {
            //说明下载的是文件
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("multipart/form-data");
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*= utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
        }

        //输出下载的文件
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
